package com.example.shop_2210.fragviewModel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.base.entity.*
import com.example.base.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

class CarViewModel:BaseViewModel() {
    //获取购物车
    val getSuccess = MutableLiveData<CarEntityResult>()
    val getFail = MutableLiveData<String>()
    fun getCar(isValid:String,page:String,limit:String){
        viewModelScope.launch {
            try {
                getSuccess.value = apiService.getCar(isValid, page, limit)
            }catch (e:Exception){
                getFail.value = e.message
            }
        }
    }
    //添加购物车
    val addCarSuccess = MutableLiveData<AddCarEntityResult>()
    val addCarFail = MutableLiveData<String>()
    //加入购物车数量  属性id   商品id
    fun addCar(cartNum:Int,productAttrUnique:String,productId:Int){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Any>()
                map.put("cartNum",cartNum)
                map.put("productAttrUnique",productAttrUnique)
                map.put("productId",productId)
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),json)
                addCarSuccess.value = apiService.addCar(body)
            }catch (e:Exception){
                addCarFail.value = e.message
            }
        }
    }

    val updateSuccess = MutableLiveData<UpdateCarEntityResult>()
    val updateFail = MutableLiveData<String>()
    fun updateCar(id:Int,number:Int){
        viewModelScope.launch {
            try {
                updateSuccess.value = apiService.updateCar(id, number)
            }catch (e:Exception){
                updateFail.value = e.message
            }
        }
    }

    val deleteSuccess = MutableLiveData<DeleteCarEntityResult>()
    val deleteFail = MutableLiveData<String>()
    fun deleteCar(ids:ArrayList<Int>){
        viewModelScope.launch {
            try {
                deleteSuccess.value = apiService.deleteCar(ids)
            }catch (e:Exception){
                deleteFail.value = e.message
            }
        }
    }

}